<template>
  <a-drawer
      :title="title"
      :visible="visible"
      :destroyOnClose="true"
      :width="400"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
  >
    <a-form layout="vertical">
      <a-form-item label="发票模板名称" v-bind="validateInfos.name">
        <a-input
            placeholder="请输入发票模板名称"
            v-model:value="modelRef.name"
        />
      </a-form-item>
      <a-form-item label="售方信息" v-bind="validateInfos.seller_id">
        <a-select
            v-model:value="modelRef.seller_id"
            placeholder="请选择售方信息"
        >
          <a-select-option
              v-for="item of sellerList"
              :key="item.id"
              :value="item.id"
          >{{ item.company_name }}
          </a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item label="税率规则" v-bind="validateInfos.tax_rule">
        <a-select
            v-model:value="modelRef.tax_rule"
            placeholder="请选择税率规则"
            mode="multiple"
        >
          <a-select-option
              v-for="item of taxRateList"
              :key="item.id"
              :value="item.id"
          >{{ item.cost_type_txt }}({{
              item.tax_code_data.tax_rate_txt
            }})
          </a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item label="是否使用电子发票" v-bind="validateInfos.e_invoice">
        <a-select
            v-model:value="modelRef.e_invoice"
            placeholder="请选择是否使用电子发票"
        >
          <a-select-option :value="0"> 不使用</a-select-option>
          <a-select-option
              v-for="item of eInvoiceList"
              :key="item.id"
              :value="item.id"
          >{{ item.title }}
          </a-select-option
          >
        </a-select>
      </a-form-item>
      <template v-if="modelRef.e_invoice == 1">
        <a-form-item label="appid" v-bind="validateInfos.spt_appid">
          <a-input
              placeholder="请输入appid"
              v-model:value="modelRef.spt_appid"
          />
        </a-form-item>
        <a-form-item label="appsecret" v-bind="validateInfos.spt_appsecret">
          <a-input
              placeholder="请输入appsecret"
              v-model:value="modelRef.spt_appsecret"
          />
        </a-form-item>
        <a-form-item label="税号" v-bind="validateInfos.spt_number">
          <a-input
              placeholder="请输入税号"
              v-model:value="modelRef.spt_number"
          />
        </a-form-item>
      </template>
      <!--      <a-form-item-->
      <!--        v-if="modelRef.e_invoice"-->
      <!--        label="后台账单缴费自动开票"-->
      <!--        v-bind="validateInfos.org_auto"-->
      <!--      >-->
      <!--        <a-switch-->
      <!--          checked-children="是"-->
      <!--          un-checked-children="否"-->
      <!--          v-model:checked="modelRef.org_auto"-->
      <!--          :checkedValue="1"-->
      <!--          :unCheckedValue="0"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <!--      <a-form-item-->
      <!--        v-if="modelRef.e_invoice"-->
      <!--        label="用户账单缴费自动开票"-->
      <!--        v-bind="validateInfos.user_auto"-->
      <!--      >-->
      <!--        <a-switch-->
      <!--          checked-children="是"-->
      <!--          un-checked-children="否"-->
      <!--          v-model:checked="modelRef.user_auto"-->
      <!--          :checkedValue="1"-->
      <!--          :unCheckedValue="0"-->
      <!--        />-->
      <!--      </a-form-item>-->

      <a-form-item label="应用楼宇" v-bind="validateInfos.build_bind">
        <a-alert
            v-if="disabledTree"
            show-icon
            type="warning"
            message="该审批流程原来绑定的项目/楼宇，您未全部选中，无法修改。"
            class="mb-10"
        />
        <ChooseHousingResources
            checkType="build"
            :allDisabled="disabledTree"
            :defaultChecked="{ buildList: checkedBuildList }"
            @request="$utils.commonRequest"
            @getResult="getResult"
            @error="setCheckedError"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  toRaw,
  toRefs,
  watch,
  ref,
} from "vue";
import {Form, message} from "ant-design-vue";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
import {ChooseHousingResources} from "bl-common-vue3";

const useForm = Form.useForm;

export default defineComponent({
  name: "AddInvoiceTemp",
  components: {ChooseHousingResources},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, {emit}) {
    const title = computed(() => {
      return props.id ? "编辑发票模板" : "新增发票模板";
    });

    const state = reactive({
      taxRateList: [],
      sellerList: [],
      checkedBuildList: [],
      disabledTree: false,
      eInvoiceList: [],
    });

    const onClose = () => {
      emit("cancel");
    };

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      name: "",
      seller_id: undefined,
      tax_rule: [],
      build_bind: undefined,
      e_invoice: 0,
      spt_appid: '',
      spt_appsecret: '',
      spt_number: "",
      // user_auto: 0,
      // org_auto: 0,
    });

    const required = [{required: true, message: "必填项"}];
    const rules = {
      name: required,
      seller_id: required,
      tax_rule: required,
      build_bind: required,
      e_invoice: required,
      // user_auto: required,
      // org_auto: required,
    };

    const rulesRef = computed(() => {
      return modelRef.e_invoice == 1
          ? {
            ...rules,
            spt_appid: required,
            spt_appsecret: required,
            spt_number: required,
          }
          : rules;
    });

    const {resetFields, validate, validateInfos} = useForm(
        modelRef,
        rulesRef
    );

    /** 选择房源 */
    const setCheckedError = (e) => {
      state.disabledTree = true;
    };
    const getResult = (info) => {
      if (state.disabledTree) {
        return;
      }
      const {villageList, buildList} = info;
      let list = [];
      if (villageList.length) {
        for (let village of villageList) {
          list = [...list, ...village.children];
        }
      }
      if (buildList.length) {
        list = [...list, ...buildList];
      }
      state.checkedBuildList = list;
    };

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      if (!state.disabledTree && state.checkedBuildList.length) {
        const buildData = utils.getProjectBuildByBuildList(
            state.checkedBuildList
        );
        modelRef.build_bind = {
          villageIds: buildData.villageId,
          buildIds: buildData.buildId,
          room: [],
        };
      }
      setTimeout(() => {
        validate().then(() => {
          const params = {...toRaw(modelRef), needMsg: true};
          const success = (res) => {
            message.success(res.msg);
            emit("success");
          };
          if (props.id) {
            params.id = props.id;
            request
                .put("/org", "/invoice/template", params)
                .then((res) => success(res));
          } else {
            request
                .post("/org", "/invoice/template", params)
                .then((res) => success(res));
          }
        });
      }, 0);
    };

    /**
     * @description: 获取编辑信息
     */
    const getEditInfo = () => {
      request
          .get("/org", "/invoice/templateInfo", {id: props.id})
          .then((res) => {
            const {detail} = res;
            setModelRef({
              name: detail.name,
              seller_id: detail.seller_id,
              tax_rule: detail.tax_rule,
              e_invoice: detail.e_invoice,
              spt_appid: detail.spt_appid,
              spt_appsecret: detail.spt_appsecret,
              spt_number: detail.spt_number,
              // user_auto: detail.user_auto,
              // org_auto: detail.org_auto,
            });
            modelRef.build_bind = detail.build_bind;
            if (detail.build_bind.buildIds) {
              state.checkedBuildList = detail.build_bind.buildIds.map((id) => ({
                id,
              }));
            }
          });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      getTaxRule();
      getSellers();
      getEInvoiceList();
      if (props.id) {
        getEditInfo();
      }
    };

    const getEInvoiceList = () => {
      request.get("/org", "/invoice/eInvoices").then((res) => {
        state.eInvoiceList = res.list;
      });
    };
    const getTaxRule = () => {
      request.get("/org", "/invoice/taxRule").then((res) => {
        state.taxRateList = res.list;
      });
    };
    const getSellers = () => {
      request.get("/org", "/invoice/sellerList").then((res) => {
        state.sellerList = res.list;
      });
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            // 打开时初始化数据
            init();
          } else {
            // 关闭时重置数据
            resetFields();
            state.checkedBuildList = [];
            state.disabledTree = false;
          }
        }
    );
    return {
      title,
      modelRef,
      validateInfos,
      ...toRefs(state),
      resetFields,
      onSubmit,
      onClose,
      setCheckedError,
      getResult,
    };
  },
});
</script>

<style lang="less" scoped></style>
